package com.yinchuang.aiuidemo;

import android.media.AudioRecord;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatTextView;

import com.iflytek.aiui.AIUIConstant;
import com.iflytek.aiui.AIUIMessage;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author Administrator
 */
public class AudioRecordActivity extends AppCompatActivity implements AIUImanager.AIUIResultEvent {
    public static String TAG = "AudioRecordActivity";
    @BindView(R.id.tv)
    AppCompatTextView mTv;
    @BindView(R.id.btn_start)
    AppCompatButton mBtnStart;
    @BindView(R.id.btn_stop)
    AppCompatButton mBtnStop;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_audiorecord);
        ButterKnife.bind(this);
        AIUImanager.setAIUIResultEvent(this);
        aiuImanager = AIUImanager.getInstance(this);
        aiuImanager.setText(mTv);
    }

    private AIUImanager aiuImanager;

    @OnClick({R.id.btn_start, R.id.btn_stop})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_start:
                mTv.setText("");
                startRecord();
                break;
            case R.id.btn_stop:
                stopRecord();
                break;
        }
    }

    private boolean isRecord;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_F5:
            case KeyEvent.KEYCODE_SEARCH:
                Log.d(TAG, "onKeyDown");
                if (aiuImanager != null && !isRecord) {
                    isRecord = true;
                    startRecord();
                    Log.d(TAG, "recording start!!!");
                }
                break;
            default:
                Log.d(TAG, "key release");
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_F5:
            case KeyEvent.KEYCODE_SEARCH:
                Log.d(TAG, "onKeyUp");
                if (aiuImanager != null && isRecord) {
                    stopRecord();
                    Log.d(TAG, "recording stop!!!");
                    isRecord = false;
                }
            default:
                Log.d(TAG, "key release");
                break;
        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    public void onSuccess(final String result) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mTv.setText(result);
            }
        });
    }

    private Thread mThread;

    private void startRecord() {
        aiuImanager.isRecord = true;
        Log.d(TAG, "startRecord");
        if (aiuImanager.getAudioRecord() == null) {
            Log.i(TAG, "create AudioRecord");
            aiuImanager.creatAudioRecord();
        }
        aiuImanager.getAudioRecord().startRecording();
        mThread = new Thread(new RecordThread());
        mThread.start();
    }

    private void stopRecord() {
        if (aiuImanager.getAudioRecord() != null) {
            aiuImanager.getAudioRecord().stop();
            aiuImanager.isRecord = false;
            aiuImanager.getAudioRecord().release();
        }
        aiuImanager.isRecord = false;
        AIUIMessage msg = new AIUIMessage(AIUIConstant.CMD_STOP_WRITE, 0, 0, params, null);
        aiuImanager.sendMessage(msg);
    }

    private String params = "data_type=audio,sample_rate=16000";

    class RecordThread implements Runnable {

        @Override
        public void run() {
            byte[] data = new byte[aiuImanager.bufferSizeInBytesAudioRecord * 2];
            while (aiuImanager.isRecord) {
                int realsize = aiuImanager.getAudioRecord().read(data, 0, aiuImanager.bufferSizeInBytesAudioRecord * 2);
                mRecorderListener.OnReceiveBytes(data, realsize);
            }
            if (!aiuImanager.isRecord) {
                aiuImanager.stopRecordAudio();
                AudioRecord audioRecord = aiuImanager.getAudioRecord();
                audioRecord.release();
                audioRecord = null;
            }
        }
    }

    private RecorderListener mRecorderListener = new RecorderListener() {
        @Override
        public void OnReceiveBytes(byte[] audiaData, int length) {
            if (null != audiaData && audiaData.length != 0) {
                byte[] audio = new byte[audiaData.length];
                System.arraycopy(audiaData, 0, audio, 0, audiaData.length);
                Log.d(TAG, "OnReceiveBytes");
                //3072byte  10-30ms
                Log.d(TAG, "audio.length:" + audio.length);
                aiuImanager.startRecordAudio(audio);
                aiuImanager.sendMessage(new AIUIMessage(AIUIConstant.CMD_WRITE, 0, 0, params, audio));
            } else {
                Log.d(TAG, "OnReceiveBytes error");
            }
        }
    };
}
